package com.googlecode.groovy_toy_orm.internal

import com.googlecode.groovy_toy_orm.internal.CodeBased

/**
 * @author: DavydovMD
 * Date: 16.04.13
 * Time: 15:23
 */
class BitMaskState<T extends Enum> implements CodeBased {
    Class<T> clazz
    private List<T> bitsOn
    int code


    public BitMaskState(Class clazz, int code){
        this.clazz = clazz
        this.code = code
        this.bitsOn =  calcBits(clazz, code)
    }

    public static <T extends Enum> BitMaskState fromCode(Class<T> clazz, Integer code){
        new BitMaskState<T>(clazz, code)
    }

//    public static <T extends Enum> BitMaskState fromList(Class<T> clazz, List<T> list){
//        int code = 0;
//
//        new BitMaskState<T>(clazz, code)
//    }

    public boolean is(T enum_value){
        bitsOn.contains(enum_value)
    }

    public List<T> getStates(){
        bitsOn.asImmutable()
    }



    protected static <T extends Enum> List calcBits(Class<T> clazz, int code){
        def values = clazz.invokeMethod("values",[] as Object[]) as List<T>
        List<T> res = [];
        values.each{
            if (code & (it.getCode() as int)) {
                res << it
            }
        }
        res
    }

    @Override
    public String toString(){
        "${this.bitsOn}"
    }

    private setCode(int code){
        this.code = code
        bitsOn = calcBits(clazz,code)
    }

}
